//
//  JBWTabBar.swift
//  新浪微博
//
//  Created by 季伯文 on 2017/6/29.
//  Copyright © 2017年 bowen. All rights reserved.
//

import UIKit

//声明协议 继承自NSObjectProtocol基协议
protocol JBWTabBarDelegate:NSObjectProtocol{
    //声明协议方法
    func composeButtonSelect()
}
class JBWTabBar: UITabBar {

    //声明闭包
    var closure:(()->())?
    
    //声明代理
    weak var jbwDelegate:JBWTabBarDelegate?
    
    override init(frame: CGRect) {
        super .init(frame: frame)
        setupUI()
    }
    required init?(coder aDecoder: NSCoder) {
        
        fatalError("init(coder:) has not been implemented")
        
    }
    //在swift中 如果把方法私有 在运行循环是找不到此方法
    //OC运行时使用kvc动态派发的方式调用方法 @objc的意思是使用OC机制来完成方法调用
    @objc private func composeButtonClick(){
        
        //执行
        jbwDelegate?.composeButtonSelect()
    }
    
    //设置视图
    private func setupUI(){
        addSubview(composeButton)
    }
    
    override func layoutSubviews() {
        super .layoutSubviews()
        //重写UIbarbutton的宽度
        let w = frame.width * 0.2
        //记录遍历到第几个标识
        var index: CGFloat = 0
        //遍历子控件UIbarbutton
        for view in subviews {
            
            if view.isKind(of: NSClassFromString("UITabBarButton")!) {
                //宽度
                view.frame.size.width = w
                //x轴
                view.frame.origin.x = w * index
                
                //index递增
                index += 1
                
                //如果等于二 再加1
                if index == 2 {
                    index += 1
                }
            }
        }
        composeButton.center.x = frame.size.width * 0.5
        composeButton.center.y = frame.size.height * 0.5
        
    }
    //懒加载按钮
    private lazy var composeButton: UIButton = {
        let btn = UIButton()
        btn.addTarget(self, action: #selector(composeButtonClick), for: UIControlEvents.touchUpInside)
        btn.setBackgroundImage(UIImage(named:"tabbar_compose_button_highlighted"), for: UIControlState.highlighted)
        btn.setBackgroundImage(UIImage(named:"tabbar_compose_button"), for: UIControlState.normal)
        btn.setImage(UIImage(named:"tabbar_compose_icon_add_highlighted"), for: UIControlState.highlighted)
        btn.setImage(UIImage(named:"tabbar_compose_icon_add"), for: UIControlState.normal)
        
        btn.sizeToFit()
        return btn
    }()
    
}
